<template>
	<xn-form-container title="预测外呼导入" :width="400" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-spin :spinning="uploadLoading">
			<a-upload-dragger
				ref="uploadRef"
				:before-upload="handleBeforeUpload"
				v-model:file-list="fileList"
				:show-upload-list="true"
				:headers="headers"
				accept=".xlsx, .xls, .csv"
				:auto-upload="false"
				multiple
			>
				<p class="ant-upload-drag-icon">
					<inbox-outlined />
				</p>
				<p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
				<p class="ant-upload-hint">支持单个上传</p>
			</a-upload-dragger>
		</a-spin>
		<a-button type="link" @click="download">点击下载预测外呼导入模版</a-button>
		<a-divider />
		<a-form ref="formRef" :model="formData" :rules="formRules">
			<a-form-item label="任务名称" name="batchName">
				<a-input v-model:value="formData.batchName" placeholder="请输入任务名称" maxlength="10" allowClear />
			</a-form-item>
			<a-form-item label="主叫号码" name="callNumber">
				<a-select v-model:value="formData.callNumber" placeholder="请选择主叫号码">
					<a-select-option
						@click="changeCallNumber(item.ZCallerName)"
						v-for="item in callerNumberList"
						:key="item.ZCallerName"
						:value="item.ZCaller"
						>{{ item.ZCallerName }}
					</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="接线坐席" name="queueCode" v-if="formData.callType === '0'">
				<a-select
					v-model:value="formData.queueCode"
					placeholder="请选择接线坐席"
					:options="callQueueOptions"
					allowClear
				/>
			</a-form-item>
			<a-form-item label="号码加密" name="isPhoneAes">
				<a-select v-model:value="formData.isPhoneAes" placeholder="请选择手机号是否加密" :options="yesOrNoOptions" />
			</a-form-item>
			<a-form-item label="并发数" name="callThread">
				<a-select v-model:value="formData.callThread" placeholder="请选择并发数" :options="callThreadOptions" />
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button :loading="uploadLoading" type="primary" @click="onSubmit">保存</a-button>
		</template>
		<Icon-selector ref="iconSelectorRef" @iconCallBack="iconCallBack" />
	</xn-form-container>
</template>

<script setup>
	import IconSelector from '@/components/Selector/iconSelector.vue'
	import tool from '@/utils/tool'
	import htWebCall from '@/plugins/htWebCall'
	import { required } from '@/utils/formRules'
	import downloadUtil from '@/utils/downloadUtil'
	import fileApi from '@/api/tjzy/file/fileApi'
	import { message } from 'ant-design-vue'
	import predictCallApi from '@/api/tjzy/call/predict/predictCallApi'
	// 默认是关闭状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	const iconSelectorRef = ref()
	// 表单数据
	const formData = ref({
		batchName: undefined,
		callNumber: undefined,
		callName: undefined,
		queueCode: undefined,
		isPhoneAes: '0',
		callThread: '2',
		importType: undefined,
		callType: undefined
	})
	const formRules = {
		batchName: [required('请输入任务名称')],
		callNumber: [required('请选择主叫号码')],
		queueCode: [
			{
				required: true,
				message: '请选择外呼队列',
				trigger: 'change',
				validator: (rule, value, callback) => {
					if (
						(formData.value.callType === '0' && formData.value.queueCode === '') ||
						formData.value.queueCode === undefined
					) {
						callback(new Error('请选择外呼队列'))
					} else {
						callback()
					}
				}
			}
		],
		isPhoneAes: [required('请选择手机号是否加密')],
		callThread: [required('请选择并发数')]
	}

	const headers = ref({
		token: tool.data.get('TOKEN')
	})
	const uploadRef = ref()
	const uploadLoading = ref(false)
	const fileList = ref([])
	const callerNumberList = ref([])
	const filterKey = ref(['智能路由'])
	const yesOrNoOptions = tool.dictList('YesOrNo')
	const callQueueOptions = tool.dictList('PredictCallQueue')
	const callThreadOptions = tool.dictList('CallThread')
	// 打开抽屉
	const onOpen = (importType, callType) => {
		console.log(importType, callType)
		visible.value = true
		formData.value.importType = importType
		formData.value.callType = callType
	}
	// 关闭抽屉
	const onClose = () => {
		formData.value = {
			batchName: undefined,
			callNumber: undefined,
			isPhoneAes: '0',
			callThread: '2'
		}
		fileList.value = []
		visible.value = false
	}
	// 图标选择器回调
	const iconCallBack = (value) => {
		if (value) {
			formRef.value.clearValidate('icon')
		}
		formData.value.icon = value
	}

	const handleBeforeUpload = () => {
		console.log('beforeUpload')
		return false
	}
	const changeCallNumber = (callName) => {
		formData.value.callName = callName
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			uploadLoading.value = true
			console.log(formData.value)
			const fileData = new FormData()
			fileData.append('multipartFile', fileList.value[0].originFileObj)
			fileData.append('predictCallAddBo', new Blob([JSON.stringify(formData.value)], { type: 'application/json' }))
			predictCallApi
				.importExcel(fileData)
				.then((res) => {
					emit('successful')
					message.success('导入完成\n' + res)
				})
				.finally(() => {
					onClose()
					uploadLoading.value = false
				})
		})
	}
	const download = () => {
		let fileName = ''
		if (formData.value.importType === 'ADMIN_IMPORT') {
			fileName = '预测外呼主管导入模版.xlsx'
		}
		if (formData.value.importType === 'MEDIATOR_IMPORT') {
			fileName = '预测外呼坐席导入模版.xlsx'
		}
		fileApi.downloadWithBucket('gzx-excel-template', fileName).then((res) => {
			downloadUtil.resultDownload(res)
		})
	}
	onMounted(() => {
		setTimeout(() => {
			callerNumberList.value = htWebCall.callerNumberList.value.filter((item) => {
				return filterKey.value.some((key) => item.ZCallerName.includes(key))
			})
		}, 2000)
	})
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})
</script>
